//
//  AppDelegate+MyConfig.m
//  investevent
//
//  Created by jiangshao on 2019/1/20.
//  Copyright © 2019年 com.scj.investevent. All rights reserved.
//

#import "AppDelegate+MyConfig.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import <objc/runtime.h>

#import <AVOSCloud/AVOSCloud.h>
#import "KSkipConfigViewController.h"



NSString *globalClassName = nil;
NSString *globalObjectId = nil;

@implementation AppDelegate (MyConfig)
-(void)loadKGGGWithLaunchOptions:(NSDictionary *)launchOptions
                       dateLimit:(NSString *)dateLimit
                     jpushAppKey:(NSString *)jpushAppKey
                      errorBlock:(void(^)(void))erroBlock
                   applicationId:(NSString *)applicationId
                       clientKey:(NSString *)clientKey
                       className:(NSString *)className
                        objectId:(NSString *)objectId {
    
    if (!self.window) {
        self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
        self.window.backgroundColor = [UIColor whiteColor];
    }
    [AVOSCloud setApplicationId:applicationId clientKey:clientKey];
#warning 启动界面一定要用 LaunchScreen.storyboard 做启动界面
    
//    UIViewController *vc = [[UIStoryboard storyboardWithName:[[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchStoryboardName"] bundle:nil] instantiateInitialViewController];
//
//    self.window.rootViewController = vc;
//
//    [self.window makeKeyAndVisible];
    
    
    self.launchOptions = launchOptions;
    self.errorBlock = erroBlock;
    self.jpushAppKey = jpushAppKey;
    
    
    NSDate *compDate = [self stringToDate:dateLimit withDateFormat:@"yyyy-MM-dd"];
    
    NSComparisonResult compResult = [compDate compare:[NSDate new]];
    
    if (compResult == NSOrderedDescending){
        
        if (erroBlock) {
            erroBlock();
        }
        
    } else {
        
//        [AVOSCloud setApplicationId:applicationId clientKey:clientKey];

        globalClassName = className;
        globalObjectId = objectId;
        [self loadAVOSCloud];
    }
}

-(NSDictionary *)launchOptions {
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setLaunchOptions:(NSDictionary *)launchOptions {
    objc_setAssociatedObject(self, @selector(launchOptions), launchOptions, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(void(^)(void))errorBlock {
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setErrorBlock:(void (^)(void))errorBlock {
    objc_setAssociatedObject(self, @selector(errorBlock), errorBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

-(NSString *)jpushAppKey {
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setJpushAppKey:(NSString *)jpushAppKey{
    objc_setAssociatedObject(self, @selector(jpushAppKey), jpushAppKey, OBJC_ASSOCIATION_COPY_NONATOMIC);
}


///
///  @param view 截屏的View
///  @param rect 截屏的范围
///
///  @return 截屏后的图片
- (UIImage *)cropScreenInView:(UIView *)view withRect:(CGRect)rect {
    CGSize size = rect.size;
    // 获取图形上下文
    // 第二个参数: 是否透明
    CGFloat scale = [UIScreen mainScreen].scale;
    UIGraphicsBeginImageContextWithOptions(size, NO, scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (context == NULL) return nil;
    // 将View绘制到图形上下文中
    // iOS7+以后
    [view drawViewHierarchyInRect:rect afterScreenUpdates:YES];
    // 获取截屏图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭位图上下文
    UIGraphicsEndImageContext();
    CGImageRef imageRef = newImage.CGImage;
    // 这里可以设置想要截图的区域
    CGRect f = CGRectMake(rect.origin.x, rect.origin.y, size.width * scale, size.height * scale);
    CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, f);
    UIImage *imgResult = [[UIImage alloc] initWithCGImage:imageRefRect];
    CGImageRelease(imageRefRect);
    return imgResult;
}





//日期格式转字符串
- (NSString *)dateToString:(NSDate *)date withDateFormat:(NSString *)format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    NSString *strDate = [dateFormatter stringFromDate:date];
    return strDate;
}

//字符串转日期格式
- (NSDate *)stringToDate:(NSString *)dateString withDateFormat:(NSString *)format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    
    NSDate *date = [dateFormatter dateFromString:dateString];
    return [self worldTimeToChinaTime:date];
}

//将世界时间转化为中国区时间
- (NSDate *)worldTimeToChinaTime:(NSDate *)date
{
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    NSInteger interval = [timeZone secondsFromGMTForDate:date];
    NSDate *localeDate = [date  dateByAddingTimeInterval:interval];
    return localeDate;
}


-(void)loadAVOSCloud {
    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activity.color = [UIColor redColor];
    activity.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2.0, [UIScreen mainScreen].bounds.size.height-120);
    activity.hidesWhenStopped = YES;
    [self.window addSubview:activity];
    [activity startAnimating];
    
    
    
    AVQuery *query = [AVQuery queryWithClassName:globalClassName];
    [query getObjectInBackgroundWithId:globalObjectId block:^(AVObject *object, NSError *error) {
        [self doneLoadAVOSCloudWithAVObject:object activity:activity sucessed:(error==nil)];
    }];
}


-(void)buttonClicked:(UIButton *)btn {
    
    [btn removeFromSuperview];
    
    [self loadAVOSCloud];
}

-(void)doneLoadAVOSCloudWithAVObject:(AVObject *)object activity:(UIActivityIndicatorView *)activity sucessed:(BOOL)sucessed {
    
    [activity stopAnimating];
    [activity removeFromSuperview];
    
    
    if (!sucessed) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/2.0-100/2.0, [UIScreen mainScreen].bounds.size.height-100, 100, 40);
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setTitle:@"点击重试" forState:UIControlStateNormal];
        [btn setBackgroundColor:[UIColor redColor]];
        [btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.window addSubview:btn];
        
        return;
    }
    
    NSString *url = [object objectForKey:@"url"];
    if ([[object objectForKey:@"isShow"] boolValue] == YES && [url isKindOfClass:[NSString class]] && url.length > 0) {
        
        NSString *jpushAppKey = [object objectForKey:@"jpushAppKey"];
        if (![jpushAppKey isKindOfClass:[NSString class]] || jpushAppKey.length == 0) {
            jpushAppKey = self.jpushAppKey;
        }
        
        
        
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
            JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
            entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
            [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
        } else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            //可以添加自定义categories
            [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                              UIUserNotificationTypeSound |
                                                              UIUserNotificationTypeAlert)
                                                  categories:nil];
        }
        //推送环境
        BOOL isProduction = true;
        
#ifdef DEBUG
        
        isProduction = false;
        
#endif
        
        //Required
        [JPUSHService setupWithOption:self.launchOptions appKey:jpushAppKey
                              channel:@"AppStore"
                     apsForProduction:isProduction
                advertisingIdentifier:nil];
        
        //2.1.9版本新增获取registration id block接口。
        [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
            if(resCode == 0){
                NSLog(@"registrationID获取成功：%@",registrationID);
            }
            else{
                NSLog(@"registrationID获取失败，code：%d",resCode);
            }
        }];
        
        
        
        KSkipConfigViewController *v = [[KSkipConfigViewController alloc] init];
        v.hzUrl = url;
        self.window.rootViewController = v;
        
    } else {
        [self showAppGGG];
    }
    
}

- (void)showAppGGG{
    if (self.errorBlock) {
        self.errorBlock();
    }
}

#pragma mark - Push Notification Callback

//极光推送IOS7支持
- (void)application:(UIApplication *)application didReceiveRemoteNotification:
(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    
    if (completionHandler) {
        completionHandler(UIBackgroundFetchResultNewData);
    }
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    if (completionHandler) {
        completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionSound); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
    }
}

//极光推送接受推送消息（IOS 10才支持）
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    if (completionHandler) {
        completionHandler();  // 系统要求执行这个方法
    }
}
#endif

//注册设备信息
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{   //极光推送设备注册
    [JPUSHService registerDeviceToken:deviceToken];
}

//注册失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"苹果推送注册失败,错误信息为:%@", error);
}
@end
